<template>
	<skeleton :skeleton="{name:'examsub'}" :showSkeleton="showSkeleton">
		<block slot="content">
			<no-data :showErrorTip="showNoData">
				<view slot="content" class="container">
					<water-mark :meta="meta"></water-mark>
					<view class="not-btn">
						<view class="head">
							<view class="head-left">
								<text class="head-text">{{getSubjectTypeDesc}}</text>
								<view class="head-textype">{{getChoiceType}}
									<image class="head-img" src="/static/exam/spot.png"></image>
								</view>
							</view>
							<view class="head-right">
								<text class="head-num">{{selfDetail.subjectNum}}/{{totalProcess}}</text>
							</view>
						</view>
						<v-question-self :subject="selfDetail" :showBox="showBox" :choiceTypeDesc="choiceType" @checkChange="checkChange"
						 @radioChange="radioChange" @judgeFlag="judgeFlag">
						</v-question-self>
						<v-analysis v-if="showAnalyse" :subject="selfDetail" />
					</view>
					<view class="btn">
						<view class="btn-left" @click="lastSub()" :class="btnDisable?'btn-disable':''">
							<text class="btn-textl">上一题</text>
						</view>
						<view class="btn-right" @click="nextSub()" :class="btnDisable?'btn-disable':''">
							<text class="btn-text">下一题</text>
						</view>
					</view>
				</view>
			</no-data>
		</block>
	</skeleton>
</template>

<script>
	import {
		isEmpty
	} from '@/utils/index';
	import examService from '@/services/exam/exam';
	import navbarExam from '@/mixins/common/navbar/exam';
	import vQuestionSelf from './fragments/vquestionself';
	import vAnalysis from './fragments/vanalysis';
	import mixins from '@/mixins/index';
	const service = new examService();
	const saveAnswer = new Set();
	export default {
		mixins: [mixins, navbarExam],
		computed: {
			getSubjectTypeDesc() {
				return this.selfDetail.subjectTypeDesc
			},
			isScene() { //是否是情景题
				return !isEmpty(this.selfDetail.subjectParentDesc);
			},
			getChoiceType() { //页面展示单选还是多选 1 单选 2 多选
				if (this.isScene) {
					return '情景题';
				} else {
					return {
						"1": '判断题',
						"2": '单选题',
						"3": '多选题',
						"4": '情景题',
						"5": '简单题',
						"6": '论述题',
						"7": '案例分析',
					} [this.selfDetail.choiceType]
				}
			},
			choiceType() {
				return {
					"1": '判断题',
					"2": '单选题',
					"3": '多选题',
					"4": '情景题',
					"5": '简单题',
					"6": '论述题',
					"7": '案例分析',
				} [this.selfDetail.choiceType]
			},
			getSubjectChoices() { //获取答案选项
				return this.selfDetail.subjectChoices
			},
			getChoice() { //获取用户选项
				return this.selfDetail.selectChoice
			},
			getAnswer() { //获取正确答案
				return this.selfDetail.answer
			},
			showAnalyse() {
				return this.selfDetail.showAnalyse
			},
		},
		data() {
			return {
				isSecond:false,
				btnDisable: false,
				showBox: false,
				selfId: '',
				finishedNum: 0,
				isAllFinished: false,
				showSkeleton: true,
				showNoData: false,
				isRoundExam: false,
				judgeSubNum: 0,
				knowledgeId: '', //知识类别
				subjectNum: 0, //当前题curProcess
				totalProcess: 0, //总题量
				ascription: "",
				selfDetail: {
					showAnalyse: false,
					subjectTypeDesc: '',
					choiceType: 1,
					subjectChoices: [],
					answer: [],
					selectChoice: [],
				},
				startTime: '',
				endTime: '',
				h: 0,
				m: 0,
				ms: 0,
				s: 0,
				time: 0,
				//str:'',
				examBarData: [{
						img: '/static/exam/examBar02.png',
						text: '收藏',
						id: 'collect',
						type: 'static',
						onPress: (context) => {
							const callback = () => context.reDrawCollect(context)
							context.collectSubject(callback)
						}
					},
					{
						img: '/static/exam/examBar04.png',
						text: '00:00:00',
						type: 'dynamics',
						id: 'time',
						onPress: (context) => {
							uni.showToast({
								title: '时间',
								duration: 2000,
								icon: 'none'
							});
						}
					}
				]
			}
		},
		components: {
			vQuestionSelf,
			vAnalysis
		},
		onLoad({
			knowledgeId,
			subjectNum,
			ascription,
			totalProcess,
			finishedNum,
			selfId,
			isSecond=false
		}) {
			this.isSecond = isSecond;
			this.knowledgeId = knowledgeId
			this.ascription = ascription
			this.totalProcess = totalProcess;
			this.finishedNum = finishedNum;
			this.selfId = selfId;
			// this.subjectNum = parseInt(subjectNum)+1
			// this.judgeSubNum = parseInt(subjectNum)+1
			let param
			if (subjectNum == totalProcess) { //题目都刷完后，用户进来默认展示第一题
				this.isAllFinished = true;
				this.subjectNum = 1
				this.judgeSubNum = parseInt(subjectNum)
			} else {
				this.subjectNum = parseInt(subjectNum) + 1
				this.judgeSubNum = parseInt(subjectNum) + 1
			}
			param = {
				knowledgeId,
				subjectNum: this.subjectNum,
				ascription
			};

			this.selfExam(param, () => this.start());
		},
		onUnload() {
			const ascription = this.ascription;
			uni.$emit('onUpdateExam', {
				code: ascription
			});
			this.reset();
		},
		methods: {
			//自主练习
			selfExam(param, callback) {
				if (this.btnDisable) {
					return;
				}
				this.btnDisable = true;
				service.selfExam({...param,isSecond:this.isSecond}).then(response => {
					this.setData(response, param, callback);
					this.btnDisable = false;
				}).then(() => {
					this.showSkeleton = false; //页面请求完成，取消骨架屏展示
				}).catch((reason) => {
					this.btnDisable = false;
				});
			},
			setData(res, param, callback) {
				if (res.success) {
					if (res.code == 202) { //当code为202时，说明库里没有查询到题目
						this.showNoData = true
						uni.showModal({
							title: '提示',
							content: res.message,
						})
						return;
					} else if (res.code == 203) { //当code为203时，说明该知识类别的题目已经做完
						if (callback != undefined) {
							callback();
						}
						return;
					}
					if (this.judgeSubNum < this.selfDetail.subjectNum) { //始终保存当前答题的，最大题数
						this.judgeSubNum = this.judgeSubNum + 1;
					}
					// res.result.showAnalyse = this.judgeSubNum>param.subjectNum;//在接口数据中添加字段，判断页面是否展示分析结果
					res.result.showAnalyse = (res.result.selectChoice.length != 0); //在接口数据中添加字段，判断页面是否展示分析结果
					this.selfDetail = res.result;
					//数据会存在已经做完过的题目，做完的题目是不计时间，入参时间传值undefinde问题处理，之间取当前数据时间回传过去
					if (this.selfDetail.useDuration != undefined) {
						this.selfDetail.duration = this.selfDetail.useDuration;
					}
					this.reDrawCollect(this); //渲染收藏按钮
					if (callback != undefined && typeof callback == 'function') {
						callback();
					}
					if (this.selfDetail.subjectNum == this.totalProcess && this.selfDetail.selectChoice.length != 0) {
						//用户刷过的试题，做循环点击试题处理
						this.isRoundExam = true
					}
				}
			},
			judgeFlag({
				callback,
				param
			}) { //判断答完后的题目，禁止学生选择
				if (this.judgeSubNum <= this.selfDetail.subjectNum && !this.selfDetail.showAnalyse) { //答完后的题目与当前真正做的题目，解析出来后控制选项不可点击
					if (!this.selfDetail.showAnalyse) {
						this.showBox = false
					}else{
						this.showBox = true
					}
					callback(param)
				}
			},
			//将秒转化为时分秒
			formateSeconds(flag = true) {
				console.log('formateSeconds')
				if (this.selfDetail.useDuration == undefined) return;

				let secondTime = parseInt(this.selfDetail.useDuration) //将传入的秒的值转化为Number
				if (flag) {
					secondTime = secondTime > 0 ? secondTime - 1 : secondTime
				}
				let m = 0 // 初始化分
				let h = 0 // 初始化小时
				let result = ''
				if (secondTime > 60) { //如果秒数大于60，将秒数转换成整数
					m = parseInt(secondTime / 60) //获取分钟，除以60取整数，得到整数分钟
					secondTime = parseInt(secondTime % 60) //获取秒数，秒数取佘，得到整数秒数
					if (m > 60) { //如果分钟大于60，将分钟转换成小时
						h = parseInt(m / 60) //获取小时，获取分钟除以60，得到整数小时
						m = parseInt(m % 60) //获取小时后取佘的分，获取分钟除以60取佘的分
					}
				}
				this.m = m;
				this.h = h;
				this.ms = 0; // secondTime*1000
				this.s = secondTime;
			},
			saveTimes() {
				let ms = 0,
					m = 0,
					h = 0;
				//将时间转换成秒保存
				if (this.ms >= 1000) { //毫秒
					ms = parseInt(this.ms / 1000)
				}
				if (this.m >= 1) { //分钟
					m = parseInt(this.m * 60)
				}
				if (this.h >= 1) { //小时
					h = parseInt(this.h * 60 * 60)
				}
				//以秒为单位保存单题做题时间
				this.selfDetail.useDuration = (ms + this.s + m + h)
				this.selfDetail.duration = this.selfDetail.useDuration

				this.h = 0;
				this.m = 0;
				this.ms = 0;
				this.s = 0;
			},
			lastSub() {
				saveAnswer.clear(); //清除答案选项的值
				//暂停重置时间，在开启时间
				this.reset()
				if (this.selfDetail.subjectNum != 1) {
					//展示前面一题
					//_this.subjectNum = parseInt(_this.selfDetail.subjectNum)-1
					const {
						knowledgeId,
						ascription
					} = this;
					let param = {
						knowledgeId,
						ascription,
						subjectNum: parseInt(this.selfDetail.subjectNum) - 1,
						isFlag: 0, //上一题
						recordId: this.selfDetail.recordId
					};
					this.selfExam(param, () => {
						this.start()
					});
				} else {
					this.tip("已经是第一题了")
				}
			},
			nextSub() {
				const {
					judgeSubNum,
					selfDetail
				} = this;
				const {
					subjectNum,
					selectChoice,
					showAnalyse
				} = selfDetail;
				if (selectChoice.length > 0) {
					if (!showAnalyse) {

						this.saveTimes()
						this.reset();
						this.selfDetail.showAnalyse = true;
						this.showBox = true

						return;
					}
					saveAnswer.clear();

					this.nextSubGo()
				} else {
					this.showBox = false
					uni.showModal({
						content: "您还没有选择答案，请答题"
					});
				}
			},
			nextSubGo() {
				//先保存当前题目时间
				//展示后面一题

				let param
				const {
					totalProcess,
					knowledgeId,
					ascription
				} = this;
				const {
					subjectNum,
					duration,
					selectChoice,
					subjectId,
					recordId
				} = this.selfDetail;
				if (this.isRoundExam) { //做过的题目从新查看时，在次点击最后一题时，不显示提交页面，传题号为1，继续播放试题
					param = {
						knowledgeId,
						subjectNum: 1,
						isFlag: 1, //下一题
						duration: duration,
						selectChoice: selectChoice.toString(),
						ascription: this.ascription,
						subjectId: subjectId,
						recordId: recordId
					};
					this.selfExam(param, () => {
						this.isRoundExam = false;
						this.start()
					});
					return
				} else {

					param = {
						knowledgeId,
						subjectNum: parseInt(subjectNum) + 1,
						isFlag: 1, //下一题
						duration: duration,
						selectChoice: selectChoice.toString(),
						ascription: this.ascription,
						subjectId: subjectId,
						recordId: recordId
					};
				}
				if (subjectNum < totalProcess) {
					// console.log('===========nextSub')
					this.selfExam(param, () => {
						this.isRoundExam = false;
						this.reset();
						this.start()
					});
				} else {
					this.selfExam(param, () => {
						const {
							finishedNum,
							selfId,
							knowledgeId,
							ascription,
							totalProcess
						} = this;
						uni.redirectTo({ //关闭当前页面，跳转到应用内的某个页面。
							url: `/pages/exam/submit?type=1&finishedNum=${finishedNum}&selfId=${selfId}&knowledgeId=${knowledgeId}&ascription=${ascription}&totalProcess=${totalProcess}&isSecond=${this.isSecond}`
						})
					});

				}
			},

			radioChange(chose) {
				for (let i = 0; i < this.getSubjectChoices.length; i++) {
					if (this.getSubjectChoices[i].choiceId == chose) {
						this.getSubjectChoices[i].isChose = 1; //0未选中，1选中
						this.selfDetail.selectChoice = Array.from(chose) //保存用户答案
					} else {
						this.getSubjectChoices[i].isChose = 0; //0未选中，1选中
					}
				}
			},
			checkChange(chose) { //多选
				//判断选中项
				for (let i = 0; i < this.getSubjectChoices.length; i++) {
					if (this.getSubjectChoices[i].choiceId == chose) {
						if (this.getSubjectChoices[i].isChose == 0) { //0未选中，1选中
							this.getSubjectChoices[i].isChose = 1;
							//保存选中项
							saveAnswer.add(chose);
						} else {
							this.getSubjectChoices[i].isChose = 0; //0未选中，1选中   取消选中
							saveAnswer.delete(chose);
						}
					}
				}
				this.selfDetail.selectChoice = Array.from(saveAnswer)

			},
			timeRender: (context, text = '00:00:01') => {
				// #ifdef APP-PLUS
				const $this = context;
				//$this.examDynamicsBar.reset();
				const {
					top
				} = context.specs;
				const richtext = `<img src="/static/exam/examBar04.png" width="27px" height="20px"/>` +
					`<br/><font style="font-size:8px;">${text}</font>`;
				$this.examDynamicsBar.drawRichText(richtext, {
						top: '9px',
						left: '0px',
						width: '100%',
						height: '100%'
					}, {
						onClick: function(e) {
							$this.examBarData[3].onPress($this);
						}
					},
					'time'
				);
				// #endif
			},
			timer(callback = () => {
				this.ms = this.ms + 1000;
			}) { //定义计时函数
				//毫秒
				if (callback != null) {
					callback();
				}
				if (this.ms >= 1000) {
					this.ms = 0;
					this.s = this.s + 1; //秒
				}
				if (this.s >= 60) {
					this.s = 0;
					this.m = this.m + 1; //分钟
				}
				if (this.m >= 60) {
					this.m = 0;
					this.h = this.h + 1; //小时
				}
				const str = this.toDub(this.h) + ":" + this.toDub(this.m) + ":" + this.toDub(this.s);
				// console.log('str:',str)
				// #ifdef APP-PLUS
				if (this.examDynamicsBar.isVisible()) {

					this.timeRender(this, str);
				}
				// #endif
			},
			start() {
				console.log(this.selfDetail.showAnalyse)
				if (this.selfDetail.showAnalyse) {
					this.showBox = true
				} else {
					this.showBox = false
				}
				if (this.isAllFinished) {
					this.formateSeconds(false);
					this.timer(null);
					return;
				}
				this.stop();
				if (!this.showAnalyse) {
					//开始
					this.time = setInterval(this.timer, 1000);
				} else {
					this.formateSeconds(false);
					this.timer(null);
				}
			},

			stop() { //暂停
				if (this.isAllFinished) {
					return;
				}
				clearInterval(this.time);
			},
			reset() { //重置
				if (this.isAllFinished) {
					return;
				}
				clearInterval(this.time);
				this.h = 0;
				this.m = 0;
				this.ms = 0;
				this.s = 0;
				//this.str="00:00:00";
			},

			toDub(n) { //补0操作
				if (n < 10) {
					return "0" + n;
				} else {
					return "" + n;
				}
			},
			tip(mes) {
				uni.showToast({
					title: mes,
					duration: 2000,
					icon: 'none'
				});
			},
			showModel(mes) {
				if (mes != undefined) {
					uni.showModal({
						title: '提示',
						content: mes,
						success: function(res) {
							if (res.confirm) {
								//console.log('用户点击确定');
							} else if (res.cancel) {
								// console.log('用户点击取消');
							}
						}
					});
				}
			},
			reDrawCollect(context) {
				// #ifdef APP-PLUS
				let collectObj = {
					img: 'examBar02',
					label: '未收藏'
				}
				if (context.selfDetail.collection == 1) {
					collectObj = {
						img: 'examBar07',
						label: '已收藏'
					}
				}
				const richtext = `<img src="/static/exam/${collectObj.img}.png" width="20px" height="20px"/>` +
					`<br/><font style="font-size:8px;">${collectObj.label}</font>`;
				console.log('reDrawCollect:')
				context.examStaticBar.drawRichText(richtext, {
						top: '9px',
						left: '0px',
						width: '32px',
						height: '100%'
					}, {
						onClick: function(e) {
							const callback = () => context.reDrawCollect(context)
							context.collectSubject(callback)
						}
					},
					'collect'
				);
				// #endif
			},
			collectSubject(callback) {
				// #ifdef APP-PLUS
				let collection = this.selfDetail.collection;
				let param = {
					subjectId: this.selfDetail.subjectId,
					type: collection, //0收藏，1取消收藏
					collectType: 1 //1，试题；2，学习
				};
				service.collectSubject(param).then(response => {
					let msg = "操作失败"
					if (response.success) {
						this.selfDetail.collection = this.selfDetail.collection == 0 ? 1 : 0
						callback();
						console.log("收藏成功", JSON.stringify(response))
						console.log("收藏成功")
						//msg = collection == 0 ? "收藏成功":"取消收藏"
						msg = "操作成功"
					}
					this.tip(msg)
				})
				// #endif
			}
		},
		onBackPress(event) {
			let _this = this
			const {
				from
			} = event;
			if (from == 'navigateBack') return false;
			uni.showModal({
				content: "确定要退出自主练习？",
				success: function(res) {
					if (res.confirm) {
						const {
							totalProcess,
							knowledgeId,
							ascription
						} = _this;
						const {
							subjectNum,
							duration,
							selectChoice,
							subjectId,
							recordId
						} = _this.selfDetail;
						if (subjectNum == totalProcess && selectChoice != 0) { //做到最后一题，用户选择后进行保存
							let param = {
								knowledgeId,
								subjectNum: parseInt(subjectNum) + 1,
								isFlag: 1, //下一题
								duration: duration,
								selectChoice: selectChoice.toString(),
								ascription: ascription,
								subjectId: subjectId,
								recordId: recordId
							};
							_this.selfExam(param);
						}
						uni.navigateBack()
					} else if (res.cancel) {
						// console.log('用户点击取消');
					}
				}
			});
			return true;
		}
	}
</script>

<style lang='scss' scoped>
	.container {
		height: 100%;
		background: #fff;
	}

	.head {
		position: relative;
		height: 100upx;
		line-height: 100upx;
		margin: 0 20upx;

		&-left {
			position: absolute;
			width: 75%;
			left: 0;
			display: flex;
		}

		&-right {
			position: absolute;
			display: inline-block;
			right: 0;
			vertical-align: middle;
			width: 20%;
			text-align: right;
		}

		&-text {
			width: 30%;
			font-size: 30upx;
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;
			color: #5ea1f8;
			font-weight: bold;
		}

		&-textype {
			font-size: 24upx;
			color: #666;
			position: relative;
			padding-left: 36upx;

			.head-img {
				width: 24upx;
				height: 28upx;
				display: inline-block;
				position: absolute;
				top: 36upx;
				left: 0;
			}
		}

		/*&-img {*/
		/*width: 24upx;*/
		/*height: 28upx;*/
		/*}*/

		/*&-textype {*/
		/*font-size: 24upx;*/
		/*color: #666;*/
		/*}*/

		&-i {
			display: inline-block;
			margin-right: 50upx;
		}

		&-ico {
			margin-top: 20upx;
			display: inline-block;
			width: 40upx;
			height: 40upx;
			text-align: center;
			background: #999;
			border-radius: 50%;
			color: #fff;
		}

		&-num {
			display: inline-block;
			color: #5ea1f8;
			font-size: 24upx;
		}
	}

	.line {
		width: 100%;
		height: 1upx;
		border-bottom: 1upx solid #eee;
	}

	.sure-btn {
		display: inline-block;
		width: 100upx;
		height: 60upx;
		line-height: 60upx;
		text-align: center;
		background-color: #5ea1f8;
		border-radius: 8upx;
		font-size: 28upx;
		color: #ffffff;
	}

	.not-btn {
		margin-bottom: 90upx;
	}

	.btn {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		text-align: center;
		line-height: 80upx;

		&-left {
			display: inline-block;
			width: 50%;
			height: 80upx;
			background: #fff;
			box-shadow: 0 -1upx 10upx #ccc;
		}

		&-right {
			display: inline-block;
			width: 50%;
			height: 80upx;
			background: #5ea1f8;
			box-shadow: 0 -1upx 10upx #ccc;
		}

		&-textl {
			font-size: 28upx;
			color: #333;
		}

		&-text {
			font-size: 28upx;
			color: #fff;
		}

		&-disable {
			background-color: #ededed;
		}
	}

	.show {
		display: block;
	}

	.hide {
		display: none;
	}
</style>

<style lang='scss'>
	page {
		height: 100%;
	}
</style>
